package site.shenjie.my.loadbalanced.config;

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
import site.shenjie.my.loadbalanced.annotation.MyLoadBalanced;
import site.shenjie.my.loadbalanced.interceptor.MyLoadBalancerInterceptor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 沈杰
 * 2020-7-24 11:56:024
 * 配置类：给 RestTemplate 注入拦截器
 */
@Configuration
public class MyLoadBalancerAutoConfiguration {
    // 提供一个获取RestTemplate的方法（供Spring给其他地方注入时调用）
    @Bean
    @MyLoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

    // 注入RestTemplate列表
    @MyLoadBalanced//自定义的@LoadBalanced
    @Autowired
    private List<RestTemplate> restTemplates = Collections.emptyList();

    @Bean
    public MyLoadBalancerInterceptor myLoadBalancerInterceptor() {
        return new MyLoadBalancerInterceptor();
    }

    /**
     * 维护一个 @MyLoadBalanced 的 RestTemplate 列表，在 SmartInitializingSingleton 中对 RestTemplate 进行拦截器设置。
     */
    @Bean
    public SmartInitializingSingleton myLoadBalancedRestTemplateInitializer() {
        return new SmartInitializingSingleton() {
            @Override
            public void afterSingletonsInstantiated() {
                for (RestTemplate restTemplate : MyLoadBalancerAutoConfiguration.this.restTemplates) {
                    List<ClientHttpRequestInterceptor> list = new ArrayList<>(restTemplate.getInterceptors());
                    list.add(myLoadBalancerInterceptor());
                    restTemplate.setInterceptors(list);
                }
            }
        };
    }
}
